#include "util.h"
#include <QDateTime>
#include <QSettings>
#include "httpclient.h"
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QtCore/QCoreApplication>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonArray>
#include <QVariantList>
#include <QFile> 
#include <QDir> 
#include <QTextStream>

//#include <alibabacloud/oss/OssClient.h>
//using namespace AlibabaCloud::OSS;

Util::Util()
{
}
Util::~Util()
{
}

QString Util::getCurrentDateTime()
{
	return QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
}

QString Util::getWeather(QString city)
{
	QString content;
	QSettings conf("util-conf.ini", QSettings::IniFormat);
	QString url = conf.value("weather/url").toString();
	
	if (!url.isEmpty() && url.contains("${location}")) {
		url.replace("${location}", city);
		qDebug() << url;
		auto httpclient = new HttpClient(NULL);

		QNetworkRequest request(url);
		QSslConfiguration config;
		QSslConfiguration conf = request.sslConfiguration();
		conf.setPeerVerifyMode(QSslSocket::VerifyNone);
		conf.setProtocol(QSsl::TlsV1SslV3);
		request.setSslConfiguration(conf);
		QNetworkReply *reply = httpclient->get(request);
		
		QObject::connect(reply, &QNetworkReply::sslErrors, [=](const QList<QSslError>& errors) {
			qDebug() << errors;
			reply->ignoreSslErrors();
		});
	

		QTime _t;
		_t.start();
		bool _timeout = false;
		while (!reply->isFinished()) {
			QCoreApplication::processEvents();
			if (_t.elapsed() >= 1000*10) {
				_timeout = true;
				break;
			}
		}

		if (!_timeout && reply->error() == QNetworkReply::NoError) {
			QString res = QString(reply->readAll());
			QJsonParseError json_error;
			QJsonDocument jsonDoc(QJsonDocument::fromJson(res.toUtf8(), &json_error));
			if (json_error.error != QJsonParseError::NoError) {
				return QString();
			}
			QJsonObject jsonobject = jsonDoc.object();
			if (jsonobject.contains("HeWeather6")) {
				QJsonValue data = jsonobject.value("HeWeather6");
				if (data.isArray()) {
					QJsonArray array = data.toArray();
					if (array.count()>0) {
						QJsonObject item = array[0].toObject();
						if (item.contains("now")) {
							QJsonObject now = item["now"].toObject();
							qDebug() << now;
							if (now.contains("cond_txt") && now.contains("tmp") && now.contains("hum") && now.contains("wind_dir")
								&&now.contains("wind_sc") && now.contains("wind_spd")) {

								content += "天气描述:" + now.value("cond_txt").toString()+", ";
								content += "温度:" + now.value("tmp").toString() + "℃, ";
								content += "湿度:" + now.value("hum").toString() + "%, ";
								content += "风向:" + now.value("wind_dir").toString() + ", ";
								content += "风力:" + now.value("wind_sc").toString() + "级, ";
								content += "风速:" + now.value("wind_spd").toString() + "km/h ";

							}
						}

					}
				}
			
			}

			qDebug() << content;
		}

		reply->deleteLater();

	}
	
	return content;
}

QString Util::getOssUrl(QString filename)
{
	
	QString content;
	/*
	QSettings conf("util-conf.ini", QSettings::IniFormat);
	std::string AccessKeyId = conf.value("oss/AccessKeyId").toString().toStdString();
	std::string AccessKeySecret = conf.value("oss/AccessKeySecret").toString().toStdString();
	std::string Endpoint = conf.value("oss/Endpoint").toString().toStdString();
	std::string BucketName = conf.value("oss/BucketName").toString().toStdString();

	
	InitializeSdk();

	ClientConfiguration config;
	OssClient client(Endpoint, AccessKeyId, AccessKeySecret, config);

	
	std::string Process = "imm/previewdoc,copy_1";
	GeneratePresignedUrlRequest request(BucketName, filename.toStdString(), Http::Get);
	request.setProcess(Process);
	int64_t timestamp = QDateTime::currentSecsSinceEpoch() + 3600;
	request.setExpires(timestamp);
	auto url = client.GeneratePresignedUrl(request);
	if (!url.isSuccess()) {
		
		std::cout << "CreateBucket fail" <<
			",code:" << url.error().Code() <<
			",message:" << url.error().Message() <<
			",requestId:" << url.error().RequestId() << std::endl;
		ShutdownSdk();
		content = url.error().Message().c_str();
		return content;
	}
	content = url.result().c_str();
	
	ShutdownSdk();*/
	
	return content;
}

QString Util::parserRandom(QJsonValue json)
{
	QString content;
	if (json.isArray()) {
		QJsonArray array = json.toArray();
		const int num = array.count();
		if (num > 1) {
			qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
			int rand = qrand() % num;
			content = json.toArray()[rand].toString();
			return content;
		}
		else if (num == 1) {
			content = json.toArray()[0].toString();
			return content;
		}
	}
	return content;
}

QJsonObject Util::matchJsonString(QString s)
{
	QJsonObject data;

	QRegularExpression re("\\$\{(.*)\}");
	QRegularExpressionMatch match = re.match(s);
	if (match.hasMatch()) {
		QString content = match.captured(0);
		content.replace("$", "");
		QJsonParseError json_error;
		QJsonDocument jsonDoc(QJsonDocument::fromJson(content.toUtf8(), &json_error));
		if (json_error.error == QJsonParseError::NoError) {
			data = jsonDoc.object();
			return data;
		}
	}
	return data;
}

void Util::toCSVFile(QJsonObject obj)
{
	QString imei,fileName,model;
	if(obj.contains("imei")){
		imei = obj.value("imei").toString();
	}
	if(imei.isEmpty()){
		qsrand(QDateTime::currentMSecsSinceEpoch());
		int num = qrand()%10000; //随机4位数据字符,填充0补齐
		QString str = QDateTime::currentDateTime().toString("yyyyMMddhhmmss")+QString("%1").arg(num,4,10,QLatin1Char('0'));
		fileName = str+QString(".csv");
	}else {
		//白名单
		QSettings conf("util-conf.ini", QSettings::IniFormat);
		QString  imeistr = conf.value("contacts/white_list").toString();
		QStringList _imeis = imeistr.split(',');
		for(QString item : _imeis){
			if(item == imei){
				return;
			}
		}
		fileName = imei+QString(".csv");
	}
	if(obj.contains("model")){
		model = obj.value("model").toString();
	}
	QString dir_path =QDir::currentPath()+QString("/csvFiles/");
	QString fullName = dir_path + fileName;
	dir_path = QDir::cleanPath(dir_path);
	QDir dir(dir_path);
	if (!dir.exists()){
		dir.mkpath(dir_path);
	}else {
		QFile file(fullName);
		if(file.exists()){
			file.remove();	
		}
		file.close();
	}

	QFile f(fullName);
	if(!f.open(QIODevice::WriteOnly | QIODevice::Text) ){  
		return;  
	} 
	QTextStream out(&f);

	//First line
	out << QString("Name,")+QString("phoneNumber,")+QString("IMEI,")+QString("phoneName,")+QString("\n");
	QJsonArray contacts = obj["contacts"].toArray();
    QVariantList list = contacts.toVariantList();
	for(QVariant item:list){
		QMap<QString,QVariant> map = item.toMap();
		QString name ,phoneNumbers;
		if(map.contains("name") && map.contains("phoneNumbers") ){
			name = map["name"].toString();
			phoneNumbers = map["phoneNumbers"].toString();
			QString line;
			line += name+QString(",");
			line += phoneNumbers+QString(",");
			line += imei+QString(",");
			line += model+QString(",")+QString("\n");
			out<< line;
		}
	}

	f.flush();
	f.close();

}
